package com.v9.system.controller;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.v9.common.dto.IdDto;
import com.v9.common.dto.PageInfoDto;
import com.v9.common.dto.TreeNodeDto;
import com.v9.common.exception.BizException;
import com.v9.common.web.AbstractController;
import com.v9.system.domain.DeptInfo;
import com.v9.system.service.DeptInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

@RestController
@Tag(name = "部门管理")
@RequestMapping(value = "/system/dept", method = RequestMethod.POST)
public class DeptInfoController extends AbstractController {

    @Resource
    private DeptInfoService deptInfoService;

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @RequestMapping("save")
    public void save(@Validated @RequestBody DeptInfo info) {
        if (info.getParentId() == null) {
            info.setStatus(true);
        }
        List<TreeNodeDto> treeNodeDtos = deptInfoService.buildTreeData();
        if (info.getId() != null && info.getParentId() != null) {
            if (info.getId().equals(info.getParentId())) {
                throw new BizException("上级部门不能等于当前部门");
            }
            TreeNodeDto current = null;
            if (treeNodeDtos != null) {
                for (TreeNodeDto item : treeNodeDtos) {
                    TreeNodeDto treeNodeDto = TreeNodeDto.find(item, info.getId().toString());
                    if (treeNodeDto != null) {
                        current = treeNodeDto;
                        break;
                    }
                }
            }
            if (current != null) {
                TreeNodeDto child = TreeNodeDto.findChild(current, info.getParentId().toString());
                if (child != null) {
                    throw new BizException("上级部门不能先择下级部门");
                }
            }

        }
        if (info.getParentId() != null) {
            StringBuilder ids = new StringBuilder();
            TreeNodeDto parent = null;
            for (TreeNodeDto item : treeNodeDtos) {
                TreeNodeDto treeNodeDto = TreeNodeDto.find(item, info.getParentId().toString());
                if (treeNodeDto != null) {
                    parent = treeNodeDto;
                }
            }
            while (parent.getParent() != null) {
                parent = parent.getParent();
                ids.append(parent.getId()).append("|");
            }

            ids.append(info.getParentId());
            info.setIds(ids.toString());
        }
        deptInfoService.saveOrInsert(info);
    }

    @RequestMapping("/view")
    @Operation(summary = "查看")
    public DeptInfo view(@RequestBody IdDto dto) {
        return deptInfoService.findById(dto.getId());

    }

    @RequestMapping("/remove")
    @Operation(summary = "删除")
    public void remove(@RequestBody IdDto dto) {
        deptInfoService.remove(false, dto.getId());
    }

    @RequestMapping("/list")
    @Operation(summary = "列表")
    public List<TreeNodeDto> list(@RequestBody DeptQueryDto dto) {
        return deptInfoService.queryTree(dto.getName());
    }

    @Data
    public static class DepartmentUpdateDto {
        @NotNull(message = "部门ID不能为空")
        @Schema(description = "部门id")
        private Long Id;
        @NotBlank(message = "部门名称不能为空")
        @Schema(description = "名称")
        private String name;
        @Schema(description = "排序")
        private Integer seq;
        @Schema(description = "备注")
        private String remark;
    }

    @Data
    public static class DeptQueryDto extends PageInfoDto {
        @Schema(description = "名称")
        private String name;
    }


    @Data
    public static class DepartmentResultDto {
        @Schema(description = "部门id")
        private Long id;
        @Schema(description = "名称")
        private String name;
        @Schema(description = "备注")
        private String remark;
        @Schema(description = "排序")
        @JsonProperty("orderNum")
        private Integer seq;
        @Schema(description = "上级部门ID")
        @JsonProperty("fatherId")
        private Long parentId;
        @Schema(description = "上级部门名称")
        private Long parentName;
        @Schema(description = "创建时间")
        private Date createTime;
        @Schema(description = "更新时间")
        private Date updateTime;
    }
}
